package cn.tedu.aop.article.service.impl;

import cn.tedu.aop.article.mapper.ArticleMapper;
import cn.tedu.aop.article.mapper.ArticleTagMapper;
import cn.tedu.aop.article.mapper.TagMapper;
import cn.tedu.aop.article.pojo.Article;
import cn.tedu.aop.article.pojo.Tag;
import cn.tedu.aop.article.service.ArticleService;
import cn.tedu.aop.base.annotation.RequiredLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(readOnly = false,
               timeout = 60,
               rollbackFor = Throwable.class,
               isolation = Isolation.READ_COMMITTED,
               propagation = Propagation.REQUIRED)
@Service
public  class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private TagMapper tagMapper;


    @RequiredLog(operation = "发布文章")
    @Override
    public void save(Article article) {
        //保存文章自身信息
        articleMapper.insert(article);
        //保存文章和标签的关系数据
        articleTagMapper.insert(article.getId(), article.getTagIds());
    }

    @CacheEvict(value = "articleCache",allEntries = true)
    //@RequiredLog(operation = "删除文章")
    @Override
    public void deleteById(Long[] ids) {
        if(ids.length==0)
            throw new IllegalArgumentException("ids不能为空");
        System.out.println("delete articles by ids");
        articleMapper.deleteById(ids);
        articleTagMapper.deleteByArticleId(ids);
    }
    @Cacheable(value = "articleCache",key = "#id")
    @Override
    public Article selectById(Long id) {
        Article article = articleMapper.selectById(id);
        List<Tag> tags = tagMapper.selectByArticleId(id);
        article.setTags(tags);
        return article;
    }

}
